<template>
  <div class="lsc-cart">
    <van-nav-bar
      title="购物车"
      :right-text="editText"
      left-arrow
      @click-left="onClickBack"
      @click-right="onClickEdit"
    />
    
    <van-checkbox-group class="card-goods" v-model="checkedGoods">
      <van-checkbox
        class="card-goods__item"
        v-for="(item,index) in goods"
        :key="index"
        :name="item.shopping_id"
      >
        <div v-if="!hasEdit">
          <van-card
            :title="item.name"
            :desc="item.model_no"
            :num="item.qty"
            :thumb="item.img_url"
          >
            <div slot="footer" v-if="!hasEdit">
              <span @click="getDemandDetails(item.shopping_id, item.prt_type, item.model_no)">详情</span>
              <!-- <van-icon name="arrow" style="font-size:14px;" @click.stop="getDemandDetails(item.shopping_id, item.prt_type, item.model_no)"/> -->
            </div>
          </van-card>
        </div>
        <div class="lsc-cart-goods_edit" v-else>
          <van-card
            :thumb="item.img_url"
          >
            <div slot="footer">
              <div class="van-card__row" @click.stop="onClickStop">
                <!-- <van-stepper
                  :min="1"
                  :max="100"
                  :default-value="item.num"/> -->
                <div class="van-stepper">
                  <button class="van-stepper__stepper van-stepper__minus van-stepper__minus--disabled" @click="onChange($event,'minus', index)"></button>
                  <input 
                    type="number" 
                    ref="num" 
                    :value="item.qty" 
                    :shopId="item.shopping_id"
                    class="van-stepper__input" 
                    @input="onInput">
                  <button class="van-stepper__stepper van-stepper__plus" @click="onChange($event,'plus', index)"></button>
                </div>
              </div>
              <div class="van-cell-swipe__right" @click.stop="onGoodsDel(index, item.shopping_id)"><span>删除</span></div>
            </div>
          </van-card>
          
        </div>
      </van-checkbox>
    </van-checkbox-group>
    <van-submit-bar
      :button-text="butText"
      @submit="onSubmit(butText)"
    >
      <van-checkbox v-model="checked">全选</van-checkbox>
    </van-submit-bar>

    <!-- 查看产品详情 -->    
    <van-popup v-model="showGoodsDetails" position="right" style="width:100%;height:100%;overflow:auto;">

      <van-nav-bar
        title="产品具体要求"
        left-arrow
        @click-left="onBackCart(1)"
      />
      
      <div v-if="hasAccesoriesType">
        <van-field
          v-model="details.prt_width"
          label="成品宽(m)"
          placeholder="请输入成品宽"
          class="lsc-goods-details-input"
        />
        <van-field
          v-model="details.prt_height"
          label="成品高(m)"
          placeholder="请输入成品高"
          class="lsc-goods-details-input"
        />
        <van-field
          v-model="details.zheshu"
          label="褶数(倍)"
          placeholder=""
          class="lsc-goods-details-input"
        />
        <van-cell title="对/单开" is-link :value="details.opentype" @click="showDdk=true"/>
        <van-cell title="打孔/捏褶" is-link :value="details.dakong" @click="showDkong=true"/>
        <van-switch-cell v-model="details.is_qianxian" title="铅线" />
        <van-switch-cell v-model="details.is_qiankuai" title="铅块" />
        <!-- <van-cell><van-checkbox class="lsc-details-pro-checkbox" v-model="choose.lichen" name="1">里衬</van-checkbox></van-cell> -->
        <van-switch-cell v-model="choose.lichen" title="里衬" />
        <div class="lsc-details-pro-checkbox-box" ref="lic"> 
          <van-cell title="型号" is-link :value="choose.lichenNo"  @click="onClickAccesories(1)"/>
          <!-- <van-field
            v-model="choose.lichenVal"
            label="宽度"
            placeholder="请输入里衬宽度"
            class="lsc-goods-details-input"
          /> -->
        </div>
        <!-- <van-cell><van-checkbox class="lsc-details-pro-checkbox" v-model="choose.zaoxing" name="2">造型</van-checkbox></van-cell> -->
        <van-switch-cell v-model="choose.zaoxing" title="造型" />
        <div class="lsc-details-pro-checkbox-box" ref="model"> 
          <van-cell title="型号" is-link :value="choose.zaoxingNo"  @click="onClickAccesories(2)"/>
          <van-field
            v-model="choose.zaoxingVal"
            label="宽度"
            placeholder="请输入造型宽度"
            class="lsc-goods-details-input"
          />
        </div>
        <!-- <van-cell><van-checkbox class="lsc-details-pro-checkbox" v-model="choose.huangGou" name="3">环/s钩</van-checkbox></van-cell> -->
        <van-switch-cell v-model="choose.huangGou" title="环/s钩" />
        <div class="lsc-details-pro-checkbox-box" ref="sgou"> 
          <van-cell title="型号" is-link :value="choose.huangGouNo"  @click="onClickAccesories(3)"/>
        </div>
      </div>
      <!-- <van-field
        v-model="details.remark"
        label="备注"
        placeholder="请输入备注"
        class="lsc-goods-details-input"
      /> -->
      <van-field
        id="remarkHeight"
        v-model="details.remark"
        label="备注"
        type="textarea"
        placeholder="请输入备注"
        class="lsc-goods-details-input"
        rows="1"
        autosize
      />

      <van-button style="margin-top: 20px;" type="primary" @click="updateCartDemand" bottom-action>确定</van-button>

    </van-popup>
    <!-- <van-dialog v-model="showGoodsRemark" @confirm="onBackCart(0)">
      <div class="lsc-goods-details-textarea">
        <span>备注</span>
        <textarea placeholder="请输入备注" rows="5" v-model="details.remark"></textarea>
      </div>
    </van-dialog> -->
    <!-- 对开，单开 -->
    <van-actionsheet v-model="showDdk" :actions="ddkActions" />
    <!-- 打孔，捏褶 -->
    <van-actionsheet v-model="showDkong" :actions="dkongActions" />
 
    <van-popup v-model="showAccesories" position="right" style="width:100%;height:100%;overflow:auto;">
      
      <van-nav-bar
        title="选择型号"
        left-arrow
        @click-left="onBackGoodsDetails"
      />
      <div v-if="accesoriesModel==1">
        <van-radio-group v-model="choose.radioLichen">
          <van-cell-group>
            <van-cell 
              v-for="(item,index) in accesories.lichen_items"
              :key="index"
              :title="item.model_no" 
              clickable @click="onChangeAccesories(1, item.id, item.model_no, item.name)">
              <van-radio :name="item.id" />
            </van-cell>
          </van-cell-group>
        </van-radio-group>
      </div>
      <div v-if="accesoriesModel==2">
        <van-radio-group v-model="choose.radioZaoxing">
          <van-cell-group>
            <van-cell 
              v-for="(item,index) in accesories.zaoxing_items"
              :key="index"
              :title="item.model_no" 
              clickable @click="onChangeAccesories(2, item.id, item.model_no, item.name)">
              <van-radio :name="item.id" />
            </van-cell>
          </van-cell-group>
        </van-radio-group>
      </div>
      <div v-if="accesoriesModel==3">
        <van-radio-group v-model="choose.radioHuangGou">
          <van-cell-group>
            <van-cell 
              v-for="(item,index) in accesoriesHG"
              :key="index"
              :title="item.model_no" 
              clickable @click="onChangeAccesories(3, item.id, item.model_no, item.name)">
              <van-radio :name="item.id" />
            </van-cell>
          </van-cell-group>
        </van-radio-group>
      </div>
      <div style="height: 50px;"></div>
    </van-popup>

    <div class="lsc-fixed-button-bottom" v-if="showAccesories">
      <van-button type="primary" @click="showAccesories = false" bottom-action>确定</van-button>
    </div>
    <div class="lsc-loading" v-if="isLoading">
      <div class="lsc-loading-mask"></div>
      <van-loading color="black" />
    </div>
  </div>
</template>

<script>
import api from '../../api'
import { mapGetters,mapState } from 'vuex'

export default {
  name: 'cart',
  computed: {
    ...mapGetters({
      isLoading: 'getLoading',
      accesories: 'getAccesories'
    })
  },
  data () {
    return {
      num: '',
      currentValue: 0,
      checked: false,
      isAllChecked: false,
      hasEdit: false,
      butText: '保存',
      editText: '编辑',
      checkedGoods: [],
      details: {},
      goods: [],
      editGoods: [],
      showDdk: false,
      ddkActions: [
        {
          name: '对开',
          callback: this.onClickDdk
        },
        {
          name: '单开',
          callback: this.onClickDdk
        }
      ],
      showDkong: false,
      dkongActions: [
        {
          name: '打孔',
          callback: this.onClickDkong
        },
        {
          name: '捏褶',
          callback: this.onClickDkong
        }
      ],
      accesoriesHG: null,
      hasAccesoriesType: false,
      showGoodsDetails: false,
      showGoodsRemark: false,
      showAccesories: false,
      accesoriesModel: 1,
      choose: {
        lichen: false,
        zaoxing: false,
        huangGou: false,
        lichenVal: '',
        zaoxingVal: '',
        lichenNo: '',
        zaoxingNo: '',
        huangGouNo: '',
        radioLichen: '',
        radioZaoxing: '',
        radioHuangGou: '',
        chooseModelNo: ''
      }
    }
  },
  created() {
    this.getCartItems()

    setTimeout(()=>{
      this.$nextTick(()=>{
      // 重置textarea高度属性
        document.querySelector('#remarkHeight').style.height = 'inherit'
        
      })
    },100)
  },
  methods: {
    getCartItems() {

      this.$store.dispatch('fetchLoading', true)
      
      this.axios.get(api.shoppingCart.cartItems)
        .then((res) => {
          this.$store.dispatch('fetchLoading', false)
          this.goods = res.data.data
        })
    },
    getDemandDetails(sp_id, p_type, model_no) {
      this.showGoodsDetails = true
      p_type==1 ? this.hasAccesoriesType = true : this.hasAccesoriesType = false
      this.choose.chooseModelNo = model_no
      let demandParams = {
        shopping_id: sp_id,
        prt_type: p_type
      }
      this.axios.get(api.shoppingCart.prtDemandDetail, {params: demandParams})
        .then((res) => {
          this.details = res.data.data
          this.choose.radioLichen = this.details.lichen ? this.details.lichen.sub_prt_id : 0
          this.choose.radioZaoxing = this.details.zaoxing ? this.details.zaoxing.sub_prt_id : 0
          this.choose.radioHuangGou = this.details.huang_gou ? this.details.huang_gou.sub_prt_id : 0
          
          this.choose.lichenNo = this.details.lichen ? this.details.lichen.model_no : ''
          this.choose.zaoxingNo = this.details.zaoxing ? this.details.zaoxing.model_no : ''
          this.choose.huangGouNo = this.details.huang_gou ? this.details.huang_gou.model_no : ''

          this.$nextTick(()=>{
            setTimeout(()=>{
              this.choose.lichenVal = this.details.lichen ? this.details.lichen.attribute_val : 0
              this.choose.zaoxingVal = this.details.zaoxing ? this.details.zaoxing.attribute_val : 0

              // 初始化 环/S钩
              let data = this.accesories.huangou_items
              if(this.details.dakong == '打孔') {
                this.accesoriesHG = data.filter(function(i) {
                  if(i.name=='环') return i;
                });
              }else {
                this.accesoriesHG = data.filter(function(i) {
                  if(i.name!='环') return i;
                });
              }
            }, 200)
          })
          this.choose.lichen = !this.choose.radioLichen ? false : true
          this.choose.zaoxing = !this.choose.radioZaoxing ? false : true
          this.choose.huangGou = !this.choose.radioHuangGou ? false : true
          // 获取各辅料选项初始值
          this.$store.dispatch('fetchAccesories', model_no)

        })
    },
    onClickStop () {
      //阻止冒泡
    },
    onClickBack() {
      // let path = this.$route.query.path || 'details'
      this.$router.push('/main')
    },
    onClickEdit() {
      if(!this.hasEdit) {
        this.hasEdit = !this.hasEdit
        this.butText = '删除'
        this.editText = '完成'
      }else {
        this.hasEdit = false
        this.butText = '保存'
        this.editText = '编辑'
        // 重新数据
        if(!this.editGoods.length) return
        this.postUpdateCart()
      }
    },
    postUpdateCart() {
      this.$toast.loading({
        duration: 0,
        message: '更新中...'
      });
      this.axios.post(api.shoppingCart.updateCart, this.editGoods)
        .then(res=>{
          if (res.data.retcode != 0) {
            this.$toast.fail(res.data.retmsg);
          }else {
            this.$toast.clear()
            this.editGoods.length = 0

            this.getCartItems()
            // 获取会员基础信息
            this.$store.dispatch('fetchBaseInfo')
          }
        })
    },
    onBackCart(bool) {
      bool ? this.showGoodsDetails = false : this.showGoodsRemark = false
    },
    onBackGoodsDetails() {
      this.showAccesories = false
    },
    onGoodsDetails(index) {
      this.showGoodsDetails = true
    },
    onGoodsDel(index, sid) {
      this.goods.splice(index, 1)

      // 过滤去重
      this.filterGoods(sid, 0, 2)
    },
    onClickAccesories(type) {
      this.showAccesories = true
      this.accesoriesModel = type
    },
    updateCartDemand() {
      
      if(!this.details.prt_width) {
        this.$toast('请填空正确的成品宽');
        return;
      }

      if(!this.details.prt_height) {
        this.$toast('请填空正确的成品高');
        return;
      }

      if(!this.details.zheshu) {
        this.$toast('请填空正确的褶数');
        return;
      }

      if(!this.choose.lichenNo && this.choose.lichen) {
        this.$toast('请选择里衬型号');
        return;
      }
      if(!this.choose.zaoxingNo && this.choose.zaoxing) {
        this.$toast('请选择造型型号');
        return;
      }
      if(!this.choose.huangGouNo && this.choose.huangGou) {
        this.$toast('请选择环/S钩型号');
        return;
      }

      const params = this.details
      delete params.lichen
      delete params.zaoxing
      delete params.huang_gou
      params.model_no = this.choose.chooseModelNo
      params.cart_details = []
      if(this.choose.lichen) {
        params.cart_details.push({
          part_name: '里衬',
          attribute: this.choose.lichenNo.split('-')[0],
          attribute_val: this.choose.lichenVal,
          sub_prt_id: this.choose.radioLichen
        })
      }
      if(this.choose.zaoxing) {
        params.cart_details.push({
          part_name: '造型',
          attribute: this.choose.zaoxingNo.split('-')[0],
          attribute_val: this.choose.zaoxingVal,
          sub_prt_id: this.choose.radioZaoxing
        })
      }
      if(this.choose.huangGou) {
        params.cart_details.push({
          part_name: '环/S钩',
          attribute: this.choose.huangGouNo.split('-')[0],
          attribute_val: 0,
          sub_prt_id: this.choose.radioHuangGou
        })
      }

      // params.cart_details = [
      //   {
      //     part_name: '里衬',
      //     attribute: this.choose.lichenNo.split('-')[0],
      //     attribute_val: this.choose.lichenVal,
      //     sub_prt_id: this.choose.radioLichen || 0
      //   },
      //   {
      //     part_name: '造型',
      //     attribute: this.choose.zaoxingNo.split('-')[0],
      //     attribute_val: this.choose.zaoxingVal,
      //     sub_prt_id: this.choose.radioZaoxing || 0
      //   },
      //   {
      //     part_name: '环/S钩',
      //     attribute: this.choose.huangGouNo.split('-')[0],
      //     attribute_val: 0,
      //     sub_prt_id: this.choose.radioHuangGou || 0
      //   }
      // ]
      console.log(params)
      this.$toast.loading({
        duration: 0,
        message: '更新中...'
      });
      this.axios.post(api.shoppingCart.updateCartDemand, params)
        .then(res=>{
          if (res.data.retcode != 0) {
            this.$toast.fail(res.data.retmsg);
          }else {
            this.$toast.clear()
            this.showGoodsDetails = false
          }
        })
    },
    onSubmit(butname) {
      if(butname == '保存') {
        if(!this.checkedGoods.length) {
          this.$toast('没有选中商品')
          return
        }

        this.$toast.loading({
          duration: 0,
          message: '保存中...'
        });
        let params = {
          shopping_ids: this.checkedGoods
        }
        this.axios.post(api.order.initial, params)
          .then(res=>{
            if (res.data.retcode != 0) {
              this.$toast.fail(res.data.retmsg);
            }else {
              this.$toast.clear()
              this.$store.dispatch('fetchOrderInfo', res.data.data)

              this.$router.push('/order')
            }
          })
      }else if(butname == '删除') {
        if(!this.checkedGoods.length) {
          this.$toast('没有选中商品')
          return
        }
        
        this.checkedGoods.forEach(element=>{
          this.filterGoods(element, 0, 2)
        })
        this.postUpdateCart()
      }
    },
    onChange(event, type, index) {
      const { value } = event.target.parentNode.childNodes[2]
      let qtys = event.target.parentNode.childNodes[2].value = type === 'minus' ? (value*1 - 1) : (value*1 + 1)

      // 修改数组数量值
      this.changeNum(index, qtys)
    },
    onInput() {
      this.changeNum()
    },
    changeNum(index, qtys) {
      const { value } = this.$refs.num[index].attributes[1]
      
      this.$refs.num.forEach((element,ind)=>{
        if(this.goods[ind].qty != element.value) {
            this.goods[ind].qty = element.value
          }
      })
      // 过滤去重
      this.filterGoods(value, qtys, 1)
      
    },
    filterGoods(val, qty, ops) {
      this.editGoods = this.editGoods.filter(t => {
        if(t.shopping_id != val) {
          return t
        }
      }) 
      
      this.editGoods.push({
        shopping_id: val,
        qty: qty,
        op_status: ops
      })
    },
    filterMinusGoods(val, qty, ops) {
      this.editGoods = this.editGoods.filter(t => {
        if(t.shopping_id == val) {
          return t
        }
      })
    },
    onClickDdk(item) {
      this.details.opentype = item.name
      this.showDdk = false
    },
    onClickDkong(item) {
      this.details.dakong = item.name
      this.choose.huangGouNo = ''
      this.onChangeAccesories(3, '', '', '')
      this.showDkong = false
      let data = this.accesories.huangou_items
      if(item.name == '打孔') {
        this.accesoriesHG = data.filter(function(i) {
          if(i.name=='环') return i;
        });
      }else {
        this.accesoriesHG = data.filter(function(i) {
          if(i.name!='环') return i;
        });
      }
    },
    onChangeAccesories(type, id, model, name) {
      if(type == 1) {
        this.choose.lichenNo = model
        this.choose.radioLichen = id
      }
      if(type == 2) {
        this.choose.zaoxingNo = model
        this.choose.radioZaoxing = id
        
        name === '帘头' ? this.choose.zaoxingVal = (1 * this.details.prt_width).toFixed(2)
                  : this.choose.zaoxingVal = (this.details.zheshu * this.details.prt_width).toFixed(2)
      }
      if(type == 3) {
        this.choose.huangGouNo = model
        this.choose.radioHuangGou = id
      }
    },
    validNumber(num) {
      let val = num.toString()
      if(val != "" && !val.match(/^[\+\-]?\d*?\.?\d*?$/)){
        this.$toast('请输入正数或小数');
        return false;
      }else{
        return true
      } 
    }
  },
  watch: {
    checkedGoods(value) {
      if(this.goods.length === value.length) {
        this.checked = true
        this.isAllChecked = false
      }else {
        this.checked = false
        this.isAllChecked = true
        value.forEach(element=>{
          this.filterMinusGoods(element, 0, 2)
        })
      }
      value.forEach(element=>{
        this.filterGoods(element, 0, 2)
      })
    },
    checked(value) {
      if(value) {
        this.checkedGoods = []
        this.goods.forEach((element,index) => {
          this.checkedGoods.push(element.shopping_id)
        });
      }else {
        if(!this.isAllChecked) {
          this.checkedGoods = []
          this.editGoods = []
        }
      }
    },
    'choose.lichen'(val) {
      if(val) {
        this.$refs.lic.style.display = 'block'
        return
      }
      
      this.$refs.lic.style.display = 'none'
    },
    'choose.zaoxing'(val) {
      if(val) {
        this.$refs.model.style.display = 'block'
        return
      }
      
      this.$refs.model.style.display = 'none'
    },
    'choose.huangGou'(val) {
      if(val) {
        this.$refs.sgou.style.display = 'block'
        return
      }
      
      this.$refs.sgou.style.display = 'none'
    },
    'details.zheshu' (val) {
      
      this.$nextTick(()=>{
        setTimeout(()=>{
          let isCheck = this.validNumber(val)
          if(!isCheck) {
            return this.details.zheshu = ''
          }
          // this.choose.lichenVal = this.choose.zaoxingVal = (this.details.prt_width * val).toFixed(2)
        }, 100)
      })
    },
    'details.prt_width' (val) {
      this.$nextTick(()=>{
        setTimeout(()=>{
          let isCheck = this.validNumber(val)
          if(!isCheck) {
            return this.details.prt_width = ''
          }
          // this.choose.lichenVal = this.choose.zaoxingVal = (this.details.zheshu * val).toFixed(2)
        }, 100)
      })
    },
    'details.prt_height' (val) {
      this.$nextTick(()=>{
        setTimeout(()=>{
          let isCheck = this.validNumber(val)
          if(!isCheck) {
            return this.details.prt_height = ''
          }
        }, 100)
      })
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style>
.lsc-cart .card-goods {
  /* padding: 10px 0; */
  /* background-color: #fff; */
  margin-bottom: 55px;
}
.lsc-cart .card-goods .card-goods__item {
    position: relative;
    background-color: #fafafa;
    margin-bottom: 4px;
}
.lsc-cart .card-goods .card-goods__item .van-checkbox__label .van-card__content {
  position: relative;
}
.lsc-cart .card-goods .card-goods__item .van-checkbox__label {
  width: 100%;
  padding: 0 10px 0 15px;
  box-sizing: border-box;
}
.lsc-cart .card-goods .card-goods__item .van-checkbox__icon {
  top: 50%;
  left: 10px;
  z-index: 1;
  position: absolute;
  margin-top: -10px;
}
.lsc-cart .van-card__row {
  margin-top: 8px;
}
/* .lsc-cart .van-card__desc {
  overflow: inherit;
} */
.lsc-cart .card-goods .card-goods__item .van-card__price {
  color: #f44;
}
.lsc-cart .card-goods .card-goods__item .van-card__info {
  color: #38f;
  font-size: 14px;
  -webkit-box-flex: 1;
  -ms-flex: 1;
  flex: 1;
  min-width: 80px;
  line-height: 20px;
  text-align: right;
}
.lsc-cart .van-cell-swipe__right {
  color: #fff;
  font-size: 15px;
  width: 70px;
  height: 90px;
  flex: 1;
  display: block;
  text-align: center;
  line-height: 90px;
  background-color: #f44;
  position: absolute;
  top: 0;
  right: 58px;
}
.lsc-cart .van-submit-bar__bar>.van-checkbox {
  margin-left: 10px;
}
.lsc-cart .lsc-cart-goods_edit .van-card__content {
  display: none
}
.lsc-cart .lsc-cart-goods_edit .van-card__footer {
  width: 100%;
  position: inherit;
  bottom: inherit;
  right: inherit;
}
.lsc-cart .lsc-goods-details-input>.van-cell__value>.van-field__control {
  text-align: right;
}
.lsc-cart .lsc-details-pro-checkbox>i {
  float: right;
}
.lsc-cart .lsc-details-pro-checkbox>span {
  margin-left: 0;
}

.lsc-cart .lsc-details-pro-checkbox-box {
  display: none;
  padding: 0 20px;
  background-color: #e5e5e5;
}
.lsc-cart .lsc-details-pro-checkbox-box .van-cell,
.lsc-cart .lsc-details-pro-checkbox-box .van-field__control {
  background-color: #e5e5e5;
}
.lsc-cart .lsc-details-pro-checkbox-box .van-cell--clickable {
  border-bottom: 1px solid rgb(131, 131, 131);
}
.lsc-cart .lsc-details-pro-checkbox-box .van-cell--clickable:last-child {
  border-bottom: 0;
}
.lsc-cart .van-switch-cell {
    border-bottom: 1px solid #f6f6f6;
}
</style>
